/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ms.square.ohos.expandabletextview.sample.utils;

import com.ms.square.ohos.expandabletextview.ExpandableTextView;
import com.ms.square.ohos.expandabletextview.sample.ResourceTable;
import com.ms.square.ohos.expandabletextview.sample.adapter.ListAdapter;
import com.ms.square.ohos.expandabletextview.sample.adapter.ViewHolder;
import ohos.agp.components.*;
import ohos.agp.render.Paint;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;

/**
 * Version 1.0
 * ModifiedBy
 * date 2021-03-15 10:13
 * description ViewCreateHelper
 */
public final class ViewCreateHelper {
    private static final HiLogLabel HI_LOG_LABEL = new HiLogLabel(HiLog.LOG_APP, 0xFFFFF, "ViewCreateHelper");
    /**
     * 列表长度
     */
    private static final int ITEM_LEN = 10;
    private static final int MAX_COLLAPSED_LINES = 4;
    private static final int DEFAULT = 2;
    private Context slice;

    /**
     * 构造函数
     *
     * @param abilitySlice Context
     */
    public ViewCreateHelper(Context abilitySlice) {
        slice = abilitySlice;
    }

    /**
     * 创建view
     *
     * @param title    标题
     * @param position 位置
     * @return Component
     */
    public Component createView(String title, int position) {
        HiLog.debug(HI_LOG_LABEL, "createView position =" + position);
        Component mainComponent;
        if (position == 0) {
            mainComponent =
                    LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_pager_srcoll_item, null, false);
            if (!(mainComponent instanceof ComponentContainer)) {
                return mainComponent;
            }
            ScrollView scrollView = (ScrollView) mainComponent.findComponentById(ResourceTable.Id_scroll);
            scrollView.enableScrollBar(1, true);
            ComponentContainer rootLayout = (ComponentContainer) mainComponent;
            DirectionalLayout root = (DirectionalLayout) rootLayout.findComponentById(ResourceTable.Id_root);
            if (null == root){
                return rootLayout;
            }
            int itemCount = root.getChildCount();
            if (itemCount > 0) {
                for (int index = 0; index < itemCount; index++) {
                    Component component = root.getComponentAt(index);
                    Text titleText = (Text) component.findComponentById(ResourceTable.Id_title);
                    titleText.setText("Sample " + (index + 1));
                    ExpandableTextView expandableTextView = (ExpandableTextView)
                            component.findComponentById(ResourceTable.Id_expandable);
                    expandableTextView.setText(slice.getString(ResourceTable.String_dummy_text2));
                    expandableTextView.setOnExpandStateChangeListener(new ExpandableTextView.OnExpandStateChangeListener() {
                        @Override
                        public void onExpandStateChanged(Text textView) {

                        }

                        @Override
                        public void expandStateChangedToast(boolean isExpanded) {
                            MyToast.show(slice, isExpanded ? "Expanded" : "Collapsed", MyToast.ToastLayout.BOTTOM);
                        }
                    });
                }
            }
            return rootLayout;
        } else {
            mainComponent =
                    LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_pager_item, null, false);
            if (!(mainComponent instanceof ComponentContainer)) {
                return mainComponent;
            }
            ComponentContainer rootLayout = (ComponentContainer) mainComponent;
            initView(mainComponent, title);
            return rootLayout;
        }
    }

    private float getFontHeight(int fontSize) {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        Paint.FontMetrics fm = paint.getFontMetrics();

        return (float) ((Math.ceil((double) fm.descent - (double) fm.top) + DEFAULT) * MAX_COLLAPSED_LINES);
    }

    ListAdapter<String> listAdapter = null;

    private void initView(Component mainComponent, String title) {
        // 列表
        ListContainer listContainer = (ListContainer) mainComponent.findComponentById(ResourceTable.Id_list_main);
        listContainer.enableScrollBar(1, true);
        listAdapter = new ListAdapter<String>(slice, ResourceTable.Layout_text_item, getData()) {
            @Override
            public void convert(ViewHolder viewHolder, String item, int position) {
                Text text = viewHolder.getView(ResourceTable.Id_expandable_text);
                text.setTag(position + "");
                text.setHeight((int) getFontHeight(text.getTextSize()));
                ExpandableTextView expandableTextView = viewHolder.getView(ResourceTable.Id_expandable);
                expandableTextView.setText(slice.getString(ResourceTable.String_dummy_text2));
                expandableTextView.setOnExpandStateChangeListener(new ExpandableTextView.OnExpandStateChangeListener() {
                    @Override
                    public void onExpandStateChanged(Text textView) {
                        int position = Integer.valueOf(textView.getTag().toString()).intValue();
                        listAdapter.notifyDataSetItemChanged(position + 1);
                    }

                    @Override
                    public void expandStateChangedToast(boolean isExpanded) {
                        MyToast.show(slice, isExpanded ? "Expanded" : "Collapsed", MyToast.ToastLayout.BOTTOM);
                    }
                });
            }
        };
        listContainer.setLayoutRefreshedListener(new Component.LayoutRefreshedListener() {
            @Override
            public void onRefreshed(Component component) {
                if (listContainer.getHeight() < ((ComponentContainer) (component.getComponentParent())).getHeight()) {
                    listContainer.setEnabled(false);
                } else {
                    listContainer.setEnabled(true);
                }
            }
        });
        listContainer.setItemProvider(listAdapter);
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int position, long l) {
            }
        });
    }

    private List<String> getData() {
        List<String> curData = new ArrayList<>();
        for (int index = 0; index < ITEM_LEN; index++) {
            curData.add("测试");
        }
        return curData;
    }
}
